# -*- coding: utf-8 -*-

from openerp import models
from openerp.osv import osv, fields, orm



#扩展发货单
class stock_picking_ext(orm.Model):
    _inherit = 'stock.picking'

    #根据出库单的关联单号找到订单的发货地址信息
    def _get_order_shipping_address(self, cr, uid, ids, name, arg, context=None):
        res = {}
        for picking in self.browse(cr, uid, ids, context=context):
            #如果出库单的关联单号存在
            if picking.origin:
                order_id = self.pool.get('sale.order').search(cr, uid, [('name','=',picking.origin)])
                order = self.pool.get('sale.order').browse(cr, uid, order_id, context=None)
                res[picking.id] = ''
                if order.partner_shipping_id.state_id:
                    res[picking.id] += order.partner_shipping_id.state_id.name
                if order.partner_shipping_id.city:
                    res[picking.id] += order.partner_shipping_id.city
                if order.partner_shipping_id.street:
                    res[picking.id] += order.partner_shipping_id.street
                #判断送货地址是否为公司，如果为公司，联系人显示企业负责人字段
                if order.partner_shipping_id.is_company:
                    if order.partner_shipping_id.principal:
                        res[picking.id] += u'\n联系人:' + order.partner_shipping_id.principal
                #如果送货地址为联系人，显示联系人的姓名
                else:
                    if order.partner_shipping_id.name:
                        res[picking.id] += u'\n联系人:' + order.partner_shipping_id.name
                if order.partner_shipping_id.phone:
                    res[picking.id] += u'\n联系电话:' + order.partner_shipping_id.phone
                if order.partner_shipping_id.mobile:
                    res[picking.id] += u'\n手机:' + order.partner_shipping_id.mobile
            else:
                res[picking.id] = u'无'
        return res

    #根据出库单的关联单号找到订单的备注信息
    def _get_order_note(self, cr, uid, ids, name, arg, context=None):
        res = {}
        for picking in self.browse(cr, uid, ids, context=context):
            #如果出库单的关联单号存在
            if picking.origin:
                #采购单
                if picking.origin.startswith('P'):
                    purchase_order_id = self.pool.get('purchase.order').search(cr, uid, [('name','=',picking.origin)])
                    purchase_order = self.pool.get('purchase.order').browse(cr, uid, purchase_order_id, context=None)
                    if purchase_order.notes:
                        res[picking.id] = purchase_order.notes
                    else:
                        res[picking.id] = u'无'
                #销售单
                else:
                    order_id = self.pool.get('sale.order').search(cr, uid, [('name', '=', picking.origin)])
                    order = self.pool.get('sale.order').browse(cr, uid, order_id, context=None)
                    if order.note:
                        res[picking.id] = order.note
                    else:
                        res[picking.id] = u'无'
            else:
                res[picking.id] = u'无'
        return res

    _columns = {
        'freight': fields.float(string=u'运费'),
        'freight_department_id': fields.many2one('hr.department', u'运费承担部门'),
        'freight_cause': fields.char(string=u'运费原因', size=255),
        #业务员
        'user_id': fields.many2one('res.users', u'业务员'),
        'move_id': fields.many2one('account.move', u'运费凭证号'),
        #订单的送货地址信息计算列
        'order_shipping_address': fields.function(_get_order_shipping_address, string=u'送货地址', type='text'),
        #订单的备注信息计算列
        'order_note': fields.function(_get_order_note, string=u'订单备注', type='text'),
        'is_printed':fields.boolean(u'是否已打印'),
        }

    #打印出货单逻辑
    def hfsy_print_picking(self, cr, uid, ids, context=None):
        '''This function prints the picking list'''
        context = dict(context or {}, active_ids=ids)
        return self.pool.get("report").get_action(cr, uid, ids, 'stock_report_picking_ext', context=context)

    #订单类型为垫付时，自动生成会计分录，状态为未记账。
    def create_account_move(self, cr, uid, ids, freight, context=None):
        """
        首先检查是否运费垫付
        如果垫付，再检查会计分录号是否存在
        如果不在即创建
        如果份录号存在，最后检查是否已记账，提示报错，否则修改
        如果运费改为0，则删除凭证
        """

        #如果是新建则不做处理
        if not ids:
            return
        
        stock_picking = self.browse(cr, 1, ids)
        partner_id = stock_picking.partner_id.id
        if not stock_picking.partner_id.is_company and stock_picking.partner_id.parent_id:
            partner_id = stock_picking.partner_id.parent_id.id
        move_id = stock_picking.move_id

        #检查是否垫付,procurement_group_id 表示需求组（关联订单等产品需求单据和拣货单）
        sale_order_id = self.pool.get('sale.order').search(cr, uid,
                                                        [('procurement_group_id', '=', stock_picking.group_id.id)])
        if sale_order_id:
            sale_order = self.pool.get('sale.order').browse(cr, uid, sale_order_id)
            #如果运费不是垫付，则返回
            if sale_order.freight_type != 'freight_paid':
                return
        #没有找到订单号,则返回
        else:
            return

        #取得凭证类型
        journal_id = self.pool['account.journal'].search(cr, 1, [('code', '=', 'DFYF')])[0]
        #当前时间
        today = fields.date.context_today(self, cr, uid, context=context)

        #如果已经存在运费分录
        if move_id:
            #如果会计分录未记账，则允许修改运费
            if move_id.state == 'draft':
                #如果运费0，则删除
                if freight == 0:
                    move_id.unlink()
                #否则修改分录
                else:
                    for line in stock_picking.move_id.line_id:
                        if line.account_id.id == stock_picking.partner_id.property_account_receivable.id:
                            line.write({'debit': freight})
                        else:
                            line.write({'credit': freight})
            else:
                raise osv.except_osv(u'警告', u'运费已经记账，不能修改！请找财务进行处理')
        elif freight != 0:
            move_id = self.pool['account.move'].create(cr, 1, {
                'journal_id': journal_id,
                'period_id': self.pool['account.period'].find(cr, 1, dt=today, context=context)[0],
                'date': fields.date.context_today(self, cr, uid),
                'ref': stock_picking.origin + u'运费',
                })

            property_account_receivable_id = self.pool['res.partner'].browse(cr, 1, partner_id).property_account_receivable.id
            default_credit_account_id_id = self.pool['account.journal'].browse(cr, 1, journal_id).default_credit_account_id.id

            self.pool['account.move.line'].create(cr, 1, {
                'move_id': move_id,
                'date': today,
                'name': u'垫付运费',
                'account_id': property_account_receivable_id,
                'debit': freight,
                'credit': 0.0,
                'partner_id': partner_id,
                })

            self.pool['account.move.line'].create(cr, 1, {
                'move_id': move_id,
                'date': today,
                'name': u'垫付运费',
                'account_id': default_credit_account_id_id,
                'debit': 0.0,
                'credit': freight,
                'partner_id': partner_id,
                })

            self.write(cr, 1, ids, {'move_id': move_id})

    #重载新建方法，自动填入部门
    def create(self, cr, user, vals, context=None):
        #判断stock.picking类型，有可能是采购单
        if vals['picking_type_id'] == 2:
            order_ids = self.pool['sale.order'].search(cr, 1, [('name', '=', vals['origin'])])
            if order_ids:
                order_id = order_ids[0]
                order = self.pool['sale.order'].browse(cr, 1, order_id, context=context)
                employee_ids = self.pool['hr.employee'].search(cr, 1, [('user_id', '=', order.user_id.id)])
                if employee_ids:
                    employee_id = employee_ids[0]
                    employee = self.pool['hr.employee'].browse(cr, 1, employee_id, context=context)
                    if employee.department_id:
                        vals['freight_department_id'] = employee.department_id.id
        return super(stock_picking_ext, self).create(cr, user, vals, context)


class express_type(osv.osv):
    """
    新建，添加，修改，快递方式
    """
    _name = 'express.type'
    _rec_name = 'name'
    _columns = {
        'name': fields.char(u'快递方式', size=64, required=True),
        'description': fields.char(u'描述', size=64),
    }
